const fs = require('fs');
const ora = require('ora'); // 实现控制台进度条样式
const chalk = require('chalk'); // 为控制台输出的文字着色
const date = require("silly-datetime");
const exec = require('child_process').exec; //异步子进程
const execSync = require('child_process').execSync; //同步子进程
const log = require('./config/log');

let user = execSync('git show -s --format=%cn').toString().trim(); //姓名
let email = execSync('git show -s --format=%ce').toString().trim(); //邮箱

let time = date.format(new Date(),'YYYY-MM-DD hh:mm:ss')

module.exports = function creatFiles(options){
    if(Array.isArray(options)){
        for(item of options){
            creatFile(item)
        }
    }else if(typeof(options)==='object') {
        creatFile(options)
    }
}

function creatFile({ 
    path, 
    name='README.md', 
    content=`##### 创建时间：${time}\n##### 创建者：${user}\n#####邮箱：${email}` 
}){
    if(!path) log('error', '创建文件 path 缺失', true);
    
    const spinner = ora('文件创建中...'); // 动画提示文字
    writeFile(`${path}`, `${name}`, content).then(res=>{
        spinner.succeed(chalk.green(res.msg));
    }).catch(err=>{
        spinner.fail(chalk.red(err.msg));
    });
}

function writeFile(path, name, content){
    let filePath = `${path}/${name}`;
    return new Promise((resolve, reject)=>{
        if(!fs.existsSync(filePath)){
            fs.writeFile(filePath, content, function(err) {
                if(err) {
                    reject({state: -1, msg: err})
                    return false;
                };
            });
            resolve({state: -1, msg: `success 文件${name}创建成功`})
        } else {
            reject({state: -1, msg: `error 文件${name}已存在`})
        }
    })
}